<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>惠农通 - 产品管理</title>
    <link rel="icon" href="./assets/logo.ico" type="images/x-ico" />
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* 产品管理页面特定样式 */
        .action-btn {
            padding: 4px 8px;
            margin: 0 4px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s;
        }
        
        .action-btn i {
            margin-right: 4px;
        }
        
        .edit-btn {
            background-color: #e6f7ff;
            color: #1890ff;
        }
        
        .edit-btn:hover {
            background-color: #bae7ff;
        }
        
        .delete-btn {
            background-color: #fff1f0;
            color: #f5222d;
        }
        
        .delete-btn:hover {
            background-color: #ffccc7;
        }
        
        /* 图片预览样式 */
        .product-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
            border: 1px solid #eee;
            transition: transform 0.3s;
        }
        
        .product-image:hover {
            transform: scale(1.8);
            z-index: 10;
            position: relative;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        /* 图片上传区域 */
        .image-upload-container {
            margin-bottom: 16px;
        }
        
        .image-upload-wrapper {
            display: flex;
            align-items: center;
            gap: 16px;
        }
        
        .image-preview {
            width: 100px;
            height: 100px;
            border: 1px dashed #d9d9d9;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            position: relative;
        }
        
        .image-preview img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        
        .upload-btn-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
        }
        
        .upload-btn {
            border: 1px solid #1890ff;
            color: #1890ff;
            background-color: #fff;
            padding: 6px 12px;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .upload-btn:hover {
            background-color: #e6f7ff;
        }
        
        .upload-btn-wrapper input[type=file] {
            font-size: 100px;
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            cursor: pointer;
        }
        
        .upload-tip {
            font-size: 12px;
            color: #999;
            margin-top: 8px;
        }
        
        /* 表格调整 */
        #productTable th:nth-child(1),
        #productTable td:nth-child(1) {
            width: 15%;
        }
        
        #productTable th:nth-child(2),
        #productTable td:nth-child(2) {
            width: 20%;
        }
        
        /* 模态框调整 */
        .modal-dialog {
            max-width: 600px;
        }
    </style>
</head>
<body>
<div class="admin-container">
    <!-- 侧边栏 -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="logo">
                <img src="assets/logo.png" alt="惠农通">
                <h2>惠农通</h2>
            </div>
        </div>
        <nav class="sidebar-menu">
            <ul>
                <li data-page="dashboard">
                    <i class="fas fa-chart-line"></i>
                    <span>数据概览</span>
                </li>
                <li data-page="employees">
                    <i class="fas fa-users"></i>
                    <span>员工管理</span>
                </li>
                <li data-page="expert">
                    <i class="fas fa-user-tie"></i>
                    <span>专家管理</span>
                </li>
                <li  data-page="farm-management">
                    <i class="fas fa-warehouse"></i>
                    <span>农场管理</span>
                </li>
                <li class="active" data-page="product">
                    <i class="fas fa-box-open"></i>
                    <span>产品管理</span>
                </li>
                <li data-page="order">
                    <i class="fas fa-shopping-cart"></i>
                    <span>订单管理</span>
                </li>
                <li data-page="ai-chat">
                    <i class="fas fa-robot"></i>
                    <span>AI问答</span>
                </li>
                <li data-page="activities">
                    <i class="fas fa-tractor"></i>
                    <span>农业活动</span>
                </li>
                <li data-page="settings">
                    <i class="fas fa-cog"></i>
                    <span>系统设置</span>
                </li>
            </ul>
        </nav>
        <div class="sidebar-footer">
            <button class="logout-btn" id="logoutBtn">
                <i class="fas fa-sign-out-alt"></i>
                <span>退出登录</span>
            </button>
        </div>
    </aside>

    <!-- 主内容区 -->
    <main class="main-content">
        <header class="main-header">
            <h1 id="pageTitle">产品管理</h1>
            <div class="user-info">
                <span class="welcome">欢迎，<span id="currentUser">管理员</span></span>
                <div class="avatar">
                    <i class="fas fa-user-circle"></i>
                </div>
            </div>
        </header>

        <!-- 产品管理页面 -->
        <div id="productsPage" class="page-content">
            <div class="page-toolbar">
                <div class="search-box">
                    <i class="fas fa-search"></i>
                    <input type="text" id="searchProductName" placeholder="输入产品名称搜索">
                    <button class="search-btn" id="searchProductBtn">搜索</button>
                </div>
                <button class="primary-btn" id="addProductBtn">
                    <i class="fas fa-plus"></i> 新增产品
                </button>
            </div>

            <div class="table-container">
                <table id="productTable">
                    <thead>
                    <tr>
                        <th>产品图片</th>
                        <th>产品名称</th>
                        <th>产品种类</th>
                        <th>产品价格</th>
                        <th>产品数量</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody></tbody>
                </table>
                <div class="loading-overlay" id="productLoading">
                    <div class="spinner"></div>
                    <span>加载中...</span>
                </div>
            </div>

            <div class="pagination-wrapper">
                <div class="pagination-controls">
                    <button class="page-btn" id="prevProductPageBtn">
                        <i class="fas fa-chevron-left"></i> 上一页
                    </button>
                    <span class="page-info" id="currentProductPage"></span>
                    <button class="page-btn" id="nextProductPageBtn">
                        下一页 <i class="fas fa-chevron-right"></i>
                    </button>
                    <select class="page-select" id="productPageSize">
                        <option value="10">每页10条</option>
                        <option value="20">每页20条</option>
                        <option value="50">每页50条</option>
                    </select>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- 产品表单模态框 -->
<div id="productModal" class="modal">
    <div class="modal-dialog">
        <div class="modal-header">
            <h3 id="productModalTitle">新增产品</h3>
            <button class="close-btn" id="closeProductModalBtn">&times;</button>
        </div>
        <form id="productForm" class="modal-body">
            <input type="hidden" id="productId">
            <div class="image-upload-container">
                <label>产品图片</label>
                <div class="image-upload-wrapper">
                    <div class="image-preview" id="imagePreview">
                        <i class="fas fa-image" style="font-size: 24px; color: #ccc;"></i>
                    </div>
                    <div class="upload-btn-wrapper">
                        <button type="button" class="upload-btn" id="uploadBtn">
                            <i class="fas fa-upload"></i> 选择图片
                        </button>
                        <input type="file" id="imageUpload" accept="image/*">
                    </div>
                </div>
                <div class="upload-tip">建议上传1:1比例的图片，大小不超过2MB</div>
                <input type="hidden" id="picture">
            </div>
            <div class="form-group">
                <label for="modalProductName">产品名称</label>
                <input type="text" id="modalProductName" placeholder="输入产品名称" required>
            </div>
            <div class="form-group">
                <label for="modalCategory">产品种类</label>
                <input type="text" id="modalCategory" placeholder="输入产品种类" required>
            </div>
            <div class="form-group">
                <label for="modalPrice">产品价格</label>
                <input type="number" id="modalPrice" placeholder="输入价格" min="0" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="modalStock">产品数量</label>
                <input type="number" id="modalStock" placeholder="输入产品数量" min="0" required>
            </div>
            <div class="form-actions">
                <button type="button" class="secondary-btn" id="cancelProductModalBtn">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button type="submit" class="primary-btn">
                    <i class="fas fa-save"></i> 保存
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    // 基础URL配置
    const BASE_URL = 'http://192.168.8.128:8080';
    // OSS上传接口URL - 请替换为您的实际接口
    const OSS_UPLOAD_URL = `${BASE_URL}/upload`;
    
    document.addEventListener('DOMContentLoaded', function() {
        // 全局变量
        let currentProductPage = 1;
        let pageSize = 10;
        let searchKeyword = '';
        const token = localStorage.getItem('token');
        
        // DOM元素
        const productTable = document.getElementById('productTable').getElementsByTagName('tbody')[0];
        const loadingOverlay = document.getElementById('productLoading');
        const prevPageBtn = document.getElementById('prevProductPageBtn');
        const nextPageBtn = document.getElementById('nextProductPageBtn');
        const currentPageSpan = document.getElementById('currentProductPage');
        const pageSizeSelect = document.getElementById('productPageSize');
        const searchInput = document.getElementById('searchProductName');
        const searchBtn = document.getElementById('searchProductBtn');
        const addProductBtn = document.getElementById('addProductBtn');
        const productModal = document.getElementById('productModal');
        const closeModalBtn = document.getElementById('closeProductModalBtn');
        const cancelModalBtn = document.getElementById('cancelProductModalBtn');
        const productForm = document.getElementById('productForm');
        const modalTitle = document.getElementById('productModalTitle');
        const imageUpload = document.getElementById('imageUpload');
        const imagePreview = document.getElementById('imagePreview');
        const pictureInput = document.getElementById('picture');
        
        // 侧边栏菜单项
        const menuItems = document.querySelectorAll('.sidebar-menu li');
        
        // 初始化页面
        initPage();
        
        // 事件监听
        prevPageBtn.addEventListener('click', goToPrevPage);
        nextPageBtn.addEventListener('click', goToNextPage);
        pageSizeSelect.addEventListener('change', changePageSize);
        searchBtn.addEventListener('click', performSearch);
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
        addProductBtn.addEventListener('click', showAddProductModal);
        closeModalBtn.addEventListener('click', hideProductModal);
        cancelModalBtn.addEventListener('click', hideProductModal);
        productForm.addEventListener('submit', handleProductSubmit);
        imageUpload.addEventListener('change', handleImageUpload);
        
        // 侧边栏菜单点击事件
        menuItems.forEach(item => {
            item.addEventListener('click', function() {
                const page = this.getAttribute('data-page');
                navigateToPage(page);
            });
        });
        
        // 页面导航函数
        function navigateToPage(page) {
            if (page === 'product') {
                window.location.href = 'product.html';
            } else if (page === 'employees') {
                window.location.href = 'employees.html';
            } else if (page === 'dashboard') {
                window.location.href = 'dashboard.html';
            } else if (page === 'login') {
                window.location.href = 'index.html';
            } else if (page === 'activities') {
                window.location.href = 'activities.html';
            } else if (page === 'settings') {
                window.location.href = 'settings.html';
            } else if (page === 'ai-chat') {
                window.location.href = 'ai-chat.html';
            } else if(page === 'expert'){
                window.location.href = 'expert.html';
            }else if(page === 'order'){
                window.location.href = 'order.html';
            }else if(page === 'farm-management'){
                window.location.href = 'farm.html';
            }
        }
        
        // 初始化页面
        function initPage() {
            setActiveMenuItem();
            loadProducts();
        }
        
        // 加载产品数据
        function loadProducts() {
            showLoading();
            
            // 构建查询参数
            const params = {
                page: currentProductPage,
                pageSize: pageSize,
                productName: searchKeyword
            };
            
            fetch(`${BASE_URL}/admin/product/page?${new URLSearchParams(params)}`,{
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
                .then(response => response.json())
                .then(data => {
                    console.log('产品数据:', data);
                    if (data.code === 1) {
                        renderProducts(data.data);
                        updatePaginationInfo();
                    } else {
                        alert('加载产品数据失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载产品数据时出错');
                })
                .finally(() => {
                    hideLoading();
                });
        }
        
        // 渲染产品表格
        function renderProducts(pageResult) {
            productTable.innerHTML = '';
            
            if (!pageResult || !pageResult.records || pageResult.records.length === 0) {
                const row = productTable.insertRow();
                const cell = row.insertCell(0);
                cell.colSpan = 6;
                cell.textContent = '没有找到产品数据';
                cell.style.textAlign = 'center';
                return;
            }
            
            pageResult.records.forEach(product => {
                const row = productTable.insertRow();
                
                // 产品图片
                const imageCell = row.insertCell(0);
                if (product.picture) {
                    const img = document.createElement('img');
                    img.src = product.picture;
                    img.alt = product.productName;
                    img.className = 'product-image';
                    imageCell.appendChild(img);
                    console.log('渲染图片:', product.picture);
                } else {
                    imageCell.innerHTML = '<i class="fas fa-image" style="color: #ccc;"></i>';
                }
                
                // 产品名称
                const nameCell = row.insertCell(1);
                nameCell.textContent = product.productName || '-';
                
                // 产品种类
                const categoryCell = row.insertCell(2);
                categoryCell.textContent = product.productType || '-';
                
                // 产品价格
                const priceCell = row.insertCell(3);
                priceCell.textContent = product.price ? `¥${product.price.toFixed(2)}` : '-';
                
                // 产品数量
                const stockCell = row.insertCell(4);
                stockCell.textContent = product.quantity || '0';
                
                // 操作
                const actionCell = row.insertCell(5);
                const editBtn = document.createElement('button');
                editBtn.className = 'action-btn edit-btn';
                editBtn.innerHTML = '<i class="fas fa-edit"></i> 编辑';
                editBtn.addEventListener('click', () => showEditProductModal(product));
                
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'action-btn delete-btn';
                deleteBtn.innerHTML = '<i class="fas fa-trash-alt"></i> 删除';
                deleteBtn.addEventListener('click', () => confirmDeleteProduct(product.productId));
                
                actionCell.appendChild(editBtn);
                actionCell.appendChild(deleteBtn);
            });
        }
        
        // 更新分页信息
        function updatePaginationInfo() {
            currentPageSpan.textContent = `第 ${currentProductPage} 页`;
            prevPageBtn.disabled = currentProductPage <= 1;
            nextPageBtn.disabled = false;
        }
        
        // 上一页
        function goToPrevPage() {
            if (currentProductPage > 1) {
                currentProductPage--;
                loadProducts();
            }
        }
        
        // 下一页
        function goToNextPage() {
            currentProductPage++;
            loadProducts();
        }
        
        // 改变每页显示数量
        function changePageSize() {
            pageSize = parseInt(pageSizeSelect.value);
            currentProductPage = 1;
            loadProducts();
        }
        
        // 执行搜索
        function performSearch() {
            searchKeyword = searchInput.value.trim();
            currentProductPage = 1;
            loadProducts();
        }
        
        // 显示加载中
        function showLoading() {
            loadingOverlay.style.display = 'flex';
        }
        
        // 隐藏加载中
        function hideLoading() {
            loadingOverlay.style.display = 'none';
        }
        
        // 显示新增产品模态框
        function showAddProductModal() {
            modalTitle.textContent = '新增产品';
            productForm.reset();
            document.getElementById('productId').value = '';
            imagePreview.innerHTML = '<i class="fas fa-image" style="font-size: 24px; color: #ccc;"></i>';
            pictureInput.value = '';
            productModal.style.display = 'flex';
        }
        
        // 显示编辑产品模态框
        function showEditProductModal(product) {
            modalTitle.textContent = '编辑产品';
            document.getElementById('productId').value = product.productId || '';
            document.getElementById('modalProductName').value = product.productName || '';
            document.getElementById('modalCategory').value = product.productType || '';
            document.getElementById('modalPrice').value = product.price || '';
            document.getElementById('modalStock').value = product.quantity || '';
            
            // 设置图片预览
            if (product.picture) {
                imagePreview.innerHTML = `<img src="${product.picture}" alt="${product.productName}">`;
                pictureInput.value = product.picture;
                console.log('设置编辑图片:', product.picture);
            } else {
                imagePreview.innerHTML = '<i class="fas fa-image" style="font-size: 24px; color: #ccc;"></i>';
                pictureInput.value = '';
            }
            
            productModal.style.display = 'flex';
        }
        
        // 隐藏产品模态框
        function hideProductModal() {
            productModal.style.display = 'none';
        }
        
        // 处理图片上传
        function handleImageUpload(e) {
            const file = e.target.files[0];
            if (!file) return;
            
            // 验证文件类型和大小
            if (!file.type.match('image.*')) {
                alert('请选择图片文件');
                return;
            }
            
            if (file.size > 2 * 1024 * 1024) {
                alert('图片大小不能超过2MB');
                return;
            }
            
            // 显示预览
            const reader = new FileReader();
            reader.onload = function(e) {
                imagePreview.innerHTML = `<img src="${e.target.result}" alt="预览">`;
            };
            reader.readAsDataURL(file);
            
            // 上传到OSS
            uploadImageToOSS(file);
        }
        
        // 上传图片到OSS
        function uploadImageToOSS(file) {
    showLoading();
    
    const formData = new FormData();
    formData.append('file', file);
    
    return fetch(OSS_UPLOAD_URL, {  // 添加return以便链式调用
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${token}`
        },
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('上传失败，状态码: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        if (data.code !== 1) {
            throw new Error(data.msg || '上传失败');
        }
        
        // 确保从正确的位置获取URL
        const pictureUrl = data.data;
        if (!pictureUrl) {
            throw new Error('未获取到有效的图片URL');
        }
        
        document.getElementById('picture').value = pictureUrl;
        console.log('成功设置picture:', pictureUrl);
        return pictureUrl; // 返回URL以便后续使用
    })
    .catch(error => {
        console.error('图片上传错误:', error);
        alert('图片上传失败: ' + error.message);
        throw error; // 重新抛出错误
    })
    .finally(() => {
        hideLoading();
    });
}
        
        // 处理产品表单提交
        function handleProductSubmit(e) {
            e.preventDefault();
            
            const productId = document.getElementById('productId').value;
            const isEdit = !!productId;

                // 确保获取picture值
            const pictureValue = document.getElementById('picture').value;
            console.log('当前picture值:', pictureValue); // 调试用
            
            const productData = {
                productName: document.getElementById('modalProductName').value.trim(),
                productType: document.getElementById('modalCategory').value.trim(),
                price: parseFloat(document.getElementById('modalPrice').value),
                quantity: parseInt(document.getElementById('modalStock').value),
                picture: pictureValue // 使用picture字段
            };
            
            console.log('准备提交的数据:', productData);
            
            if (isEdit) {
                productData.productId = productId;
                updateProduct(productData);
            } else {
                addProduct(productData);
            }
        }
        
        // 添加产品
        function addProduct(productData) {
            showLoading();
            
            fetch(`${BASE_URL}/admin/product`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(productData)
            })
            .then(response => response.json())
            .then(data => {
                console.log('添加返回:', data);
                if (data.code === 1) {
                    alert('产品添加成功');
                    hideProductModal();
                    loadProducts();
                } else {
                    alert('添加产品失败: ' + data.msg);
                }
            })
            .catch(error => {
                console.error('添加错误:', error);
                alert('添加产品时出错');
            })
            .finally(() => {
                hideLoading();
            });
        }
        
        // 更新产品
        function updateProduct(productData) {
            showLoading();
            const productId = document.getElementById('productId').value;
            
            console.log('准备更新的数据:', productData);
            
            fetch(`${BASE_URL}/admin/product/${productId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(productData)
            })
            .then(response => response.json())
            .then(data => {
                console.log('更新返回:', data);
                if (data.code === 1) {
                    alert('产品更新成功');
                    hideProductModal();
                    loadProducts();
                } else {
                    alert('更新产品失败: ' + data.msg);
                }
            })
            .catch(error => {
                console.error('更新错误:', error);
                alert('更新产品时出错');
            })
            .finally(() => {
                hideLoading();
            });
        }
        
        // 确认删除产品
        function confirmDeleteProduct(productId) {
            if (confirm('确定要删除这个产品吗？此操作不可恢复。')) {
                deleteProduct(productId);
            }
        }
        
        // 删除产品
        function deleteProduct(id) {
            showLoading();
            fetch(`${BASE_URL}/admin/product/${id}`,{
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => response.json())
            .then(data => {
                console.log('删除返回:', data);
                if (data.code === 1) {
                    alert('产品删除成功');
                    loadProducts();
                } else {
                    alert('删除产品失败: ' + data.msg);
                }
            })
            .catch(error => {
                console.error('删除错误:', error);
                alert('删除产品时出错');
            })
            .finally(() => {
                hideLoading();
            });
        }

        function setActiveMenuItem() {
            const currentPage = window.location.pathname.split('/').pop().replace('.html', '');
            document.querySelectorAll('.sidebar-menu li').forEach(item => {
                item.classList.remove('active');
                if (item.getAttribute('data-page') === currentPage) {
                    item.classList.add('active');
                }
            });
        }
    });
</script>
</body>
</html>